package org.csu.xzypetstore.controller;

import org.csu.xzypetstore.domain.*;
import org.csu.xzypetstore.service.CatalogService;
import org.csu.xzypetstore.service.orderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.annotation.SessionScope;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.PushBuilder;
import java.util.Iterator;

@Controller
@SessionScope
@RequestMapping("/cart/")
@SessionAttributes({"cart","order","lineItems"})
public class CartController {

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private Cart cart;

    @Autowired
    private Account account;

    @Autowired
    private orderService orderService;

    @GetMapping("viewCart")
    public String viewCart(Model model){
        model.addAttribute("cart",cart);
        return "cart/cart";
    }

    @GetMapping("addItemToCart")
    public String addItemToCart(String workingItemId, Model model){
        if(cart.containsItemId(workingItemId)){
            cart.incrementQuantityByItemId(workingItemId);
        }else{
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item,isInStock);
        }
        model.addAttribute("cart",cart);
        return "cart/cart";
    }

    @GetMapping("removeItemFromCart")
    public String removeItemFromCart(String workingItemId, Model model){
        Item item = cart.removeItemById(workingItemId);
        model.addAttribute("cart",cart);
        if(item == null){
            model.addAttribute("msg", "Attempted to remove null CartItem from Cart.");
            return "common/error";
        }else{
            return "cart/cart";
        }
    }

    @PostMapping("updateCartQuantities")
    public String updateCartQuantities(HttpServletRequest request, Model model){
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while (cartItems.hasNext()){
            CartItem cartItem = cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try{
                int quantity = Integer.parseInt(request.getParameter(itemId));
                cart.setQuantityByItemId(itemId,quantity);
                if(quantity < 1){
                    cartItems.remove();
                }
            }catch (Exception e){

            }
        }
        model.addAttribute("cart",cart);
        return "cart/cart";
    }

    @GetMapping("order")
    public String ViewOrder(Model model,HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        cart = (Cart) session.getAttribute("cart");
        account = (Account) session.getAttribute("account");
        if(cart==null)
        {
            cart = new Cart();
            model.addAttribute("cart",cart);
        }
        if(account==null)
            return "account/SignonForm";
        else {
            Order order = new Order();
            order.initOrder(account,cart);

            model.addAttribute("creditCardTypes",order.getCardType());
            model.addAttribute("order",order);
            return "order/orderForm";
        }
    }

    @PostMapping("confirmOrder")
    public String ConfirmOrder(HttpServletRequest request, Model model)
    {
        HttpSession session = request.getSession();

        String cardType = request.getParameter("cardType");
        String creditCard = request.getParameter("creditCard");
        String expiryDate = request.getParameter("expiryDate");
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String address1 = request.getParameter("address1");
        String address2 = request.getParameter("address2");
        String city = request.getParameter("city");
        String state = request.getParameter("state");
        String zip = request.getParameter("zip");
        String country = request.getParameter("country");
        String post="no";

        // 修改订单消息
        Order order = (Order)session.getAttribute("order");
        order.setCardType(cardType);
        order.setCreditCard(creditCard);
        order.setExpiryDate(expiryDate);
        order.setBillToFirstName(firstName);
        order.setBillToLastName(lastName);
        order.setShipToFirstName(firstName);
        order.setShipToLastName(lastName);
        order.setBillAddress1(address1);
        order.setBillAddress2(address2);
        order.setShipAddress1(address1);
        order.setShipAddress2(address2);
        order.setBillCity(city);
        order.setShipCity(city);
        order.setBillState(state);
        order.setShipState(state);
        order.setBillZip(zip);
        order.setShipZip(zip);
        order.setBillCountry(country);
        order.setShipCountry(country);
        order.setPost(post);

        model.addAttribute("order",order);
        if(request.getParameter("shippingAddressRequired") != null)
            return "order/orderForm";
        else
            return "order/confirmOrder";
    }

    @GetMapping("viewOrder")
    public String ViewOrder(HttpServletRequest request,Model model)
    {
        HttpSession session = request.getSession();
        Order order = (Order)session.getAttribute("order");

        model.addAttribute("lineItems",order.getLineItems());
        //插入信息
        System.out.println(account + ",,,,,,,,,,,,,,,,,,,,,,,,,,,,,");
        orderService.insertOrder(order);

        //重置购物车
        cart = new Cart();
        model.addAttribute("cart",cart);
        return "order/viewOrder";
    }


}
